import { IDeviceCategory, IResponse } from '@/interfaces/common.interface';
import { Button, Cell, DropdownItem, DropdownMenu, Field, Icon, Switch } from 'vant';
import { Component, Vue } from 'vue-property-decorator';
import style from '../styles/device.module.less';

@Component({
  components: {
    'van-button': Button,
    'van-field': Field,
    'van-dropdown-menu': DropdownMenu,
    'van-dropdown-item': DropdownItem,
    'van-cell': Cell,
    'van-switch': Switch,
    'van-icon': Icon
  },
  sockets: {
    message(data: { type: IDeviceCategory; data: string }) {
      console.log('message: ', data);
      if (data.type === 'coap') {
        this.$data.receiveMessage = data.data;
      }
    }
  }
})
export default class Coap extends Vue {
  private sendMessage = '';
  private receiveMessage = '';
  private coapDeviceAddr = 'coap://192.168.128.108:5683';
  private coapPath = 'test';

  private get hasCoapPermission() {
    return this.$store.state.permissions && this.$store.state.permissions.coap;
  }

  private get validServerAddr() {
    const onlyHostReg = /^coap:\/\/((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/;
    if (onlyHostReg.test(this.coapDeviceAddr)) {
      return true;
    } else {
      const arr = this.coapDeviceAddr.split(':');
      if (arr[2] && arr[2].length <= 5 && Number(arr[2]) <= 65535) {
        return true;
      } else {
        return false;
      }
    }
  }

  public render() {
    return (
      <div class={style['device-message']}>
        <p class={style['device-message-title']}>【Server 地址】:</p>
        <van-field
          v-model={this.coapDeviceAddr}
          label='COAP地址：'
          placeholder='COAP服务端地址'
          error-message={!this.validServerAddr && '服务地址不符合标准'}></van-field>
        <van-field label='资源路径：' v-model={this.coapPath} placeholder='资源路径 eg：test'></van-field>
        <div class={style['device-message-content']}>
          <p class={style['device-message-title']}>
            【COAP GET】：
            {this.coapDeviceAddr && (
              <van-button
                size='small'
                on-click={this.connectServer}
                plain
                hairline
                color='#20a5de'
                disabled={!this.validServerAddr}>
                获取路径数据
              </van-button>
            )}
          </p>
          <van-field
            value={this.receiveMessage}
            readonly
            rows='3'
            autosize
            type='textarea'
            placeholder='coap响应数据'></van-field>

          <p class={style['device-message-title']}>
            【COAP PUT】：
            {this.coapDeviceAddr && (
              <van-button
                size='small'
                on-click={this.submitMessage}
                plain
                hairline
                color='#20a5de'
                disabled={!this.validServerAddr}>
                修改路径数据
              </van-button>
            )}
          </p>
          <div class={style['device-message-send']}>
            <van-field
              v-model={this.sendMessage}
              rows='3'
              autosize
              type='textarea'
              placeholder='请输入要修改路径的内容'
            />
          </div>
        </div>

        {/* 权限判断 */}
        {!this.hasCoapPermission && (
          <div class={style['permission']}>
            <p>
              当前模块需要开启<span>{` COAP `}</span>，请按照以下路径进行手动配置：
            </p>
            <span>{`设置 > 隐私设置 > 应用权限 > 设备通信 > 系统权限 > ...`}</span>
          </div>
        )}
      </div>
    );
  }

  private connectServer() {
    this.$socket.client.emit('connect-coap', this.coapDeviceAddr, this.coapPath, (res: IResponse) => {
      if (!res || !res.result) {
        this.$edger.notify.error(res.message || '获取Coap指定路径信息失败！');
      } else {
        this.receiveMessage = res.data;
        this.$edger.notify.success(res.message || '获取Coap指定路径信息成功！');
      }
    });
  }

  /* 发送设备消息 */
  private submitMessage() {
    this.$socket.client.emit(
      'send-message',
      { type: 'coap', data: { url: this.coapDeviceAddr, path: this.coapPath, data: this.sendMessage } },
      (res: any) => {
        if (!res || !res.result) {
          this.$edger.notify.error(res.message || '修改Coap指定路径信息失败！');
        } else {
          this.$edger.notify.success(res.message || '修改Coap指定路径信息成功！');
        }
      }
    );
  }
}
